package com.xie.o2o.service.impl;

import com.xie.o2o.cache.JedisUtil;
import com.xie.o2o.dao.AreaDao;
import com.xie.o2o.entity.Area;
import com.xie.o2o.service.AreaService;
import com.xie.o2o.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @create: xie
 */
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private JedisUtil.Keys jedisKeys;
    @Autowired
    private JedisUtil.Strings jedisStrings;

    /**
     * 第一次查询存入redis缓存
     * 后续查询判断redis是否存在key，存在从redis获取
     *
     * @return
     */
    @Override
    @Transactional
    public List<Area> getAreaList() {
        //设置redis存储的key
        String key = AREALISTKEY;
        List<Area> areaList;
        String s;
        //如果key不存在
        if (!jedisKeys.exists(key)) {
            //第一次从数据库查询
            areaList = areaDao.queryArea();
            //把list转换成string
            s = JsonUtil.obj2String(areaList);
            //缓存在redis
            jedisStrings.set(key, s);
        } else {
            //Redis存在key，从redis获取
            s = jedisStrings.get(key);
            areaList = JsonUtil.string2Obj(s, ArrayList.class, Area.class);

        }
        return areaList;
    }
}
